package org.zsk.cs.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zsk.cs.domain.po.Role;
import org.zsk.cs.dao.RoleDao;
import org.zsk.cs.domain.vo.RoleVo;
import org.zsk.cs.service.RoleService;
import org.zsk.fastdev.assign.Assign;
import org.zsk.fastdev.bean.BeanUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色 serviceImpl
 * </p>
 *
 * @author zsk
 * @version 1.0
 * Created on 2020/03/26
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl extends ServiceImpl<RoleDao,Role> implements RoleService {

    private final RoleDao roleDao;
    private final Assign assign;

    @Autowired
    public RoleServiceImpl(RoleDao roleDao, Assign assign) {
        this.roleDao = roleDao;
        this.assign = assign;
    }

    @Override
    public boolean addMenuForRoleBatch(List<Integer> rList, List<Integer> mList){
        Map<String, List<Integer>> map=new HashMap<>(2);
        map.put("rList", rList);
        map.put("mList", mList);
        return roleDao.addMenuForRoleBatch(map)>0;
    }

    @Override
    public boolean updateMenuForRoleBatch(List<Integer> rList, List<Integer> mList){
        rList.forEach(roleDao::deleteAllMenuForRole);
        if (mList.size()<=0){
            log.debug("清空该角色所有权限");
            return true;
        }
        return this.addMenuForRoleBatch(rList,mList);
    }

    @Override
    public boolean addUserForRoleBatch(List<Long> uList, List<Integer> rList) {
        Map<String, List<? extends Number>> map=new HashMap<>(2);
        map.put("uList", uList);
        map.put("rList", rList);
        return roleDao.addUserForRoleBatch(map)>0;
    }

    @Override
    public boolean updateUserForRoleBatch(List<Long> uList, List<Integer> rList) {
        rList.forEach(roleDao::deleteAllUserForRole);
        if (uList.size()<=0){
            log.debug("清空该角色所有用户");
            return true;
        }
        return this.addUserForRoleBatch(uList,rList);
    }

    @Override
    public List<Integer> getMenuIdByRoleId(Integer roleId){
        return roleDao.selectMenuIdByRoleId(roleId);
    }

    @Override
    public List<Integer> getUserIdByRoleId(Integer roleId){
        return roleDao.selectUserIdByRoleId(roleId);
    }

    @Override
    public Page<Role> search(RoleVo roleVo) throws Exception {
        Role role=new Role();
        Page<Role> page=new Page<>();
        assign.assign(roleVo,role,"name,zhName");
        assign.assign(roleVo,page,"$current,$size");
        return roleDao.selectPage(page, BeanUtils.bean2QueryWrapper(Role.class,role));
    }
}
